# -*- coding: utf-8 -*-
# created on 2016/12/19

from operator import itemgetter
from sympy import latex
from mathsolver.functions.base import BaseFunction, BaseIneqs, BaseEq, BaseValue
from mathsolver.functions.hanshu.zhiyu import hanshuzuizhi
from mathsolver.functions.hanshu.helper import reverse_op


class ChuDengHanShuBiJiao(BaseFunction):
    """基本初等函数比较大小"""

    def solver(self, *args):
        eqs = args[0].sympify()
        eqs = [[sym, expr.evalf()] for sym, expr in eqs]
        eqs.sort(reverse=True, key=itemgetter(1))
        order_desc = [str(sym) for sym, expr in eqs]
        res = BaseIneqs(' > '.join(order_desc).split(' '))

        self.label.add("基本初等函数比较大小")
        self.output.append(res)
        return self


class DanDiaoBiJiao(BaseFunction):
    """hs052.函数单调性比较大小"""

    def solver(self, *args):
        qujian, dandiao, f1, f2 = args
        f1_var, f2_var = f1.var, f2.var

        if f2_var.free_symbols or f2_var.free_symbols:
            # 若含有参数，求 f1_var - f2_var 的最值
            expr = f1_var - f2_var
            zuida, zuixiao = hanshuzuizhi().solver(BaseEq(["y", expr]), qujian).output[0].value
            # 若最大值 < 0, f1_var < f2_var 恒成立
            if zuida < 0:
                relation = '<'
            elif zuida <= 0:
                relation = '<='
            # 若最小值 > 0, f1_var > f2_var 恒成立
            elif zuixiao > 0:
                relation = '>'
            elif zuixiao >= 0:
                relation = '>='
            else:
                raise ValueError("无法判别单调性")

            self.steps.append(["", "%s %s %s 在 %s 上恒成立" % (f1_var, relation, f2_var, latex(qujian))])

        else:
            if f1_var > f2_var:
                relation = '>'
            elif f1_var < f2_var:
                relation = '<'
            elif f1_var == f2_var:
                relation = '='
            else:
                raise ValueError("无法判别单调性")
            self.steps.append(["", "%s %s %s" % (f1_var, relation, f2_var)])

        res = relation if '增' in dandiao or relation == '=' else reverse_op(relation)
        self.steps.append(["", "所以 %s %s %s" % (f1.printing(), res, f2.printing())])
        self.output.append(BaseValue(res))
        return self


if __name__ == '__main__':
    pass
